package org.crsystems.crbooks.models;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.CascadeType;
import javax.persistence.FetchType;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.vaadin.annotations.AutoGenerated;

@Entity
@Table(name="Authors")
public class Author extends ModelBase<Author, Integer> {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(updatable = false, nullable = false)
	private Integer authorID;
	
	@Basic
	private String name;
	
	@Basic
	private String description;

	public void setBooks(List<Book> books) {
		for (Book book : books) {
			book.setAuthor(this);
		}
	}

	public List<Book> getBooks() {
		return Book.getByAuthor(this);
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@Override
	public String getTableName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isValid() {
		return false;
	}

	@Override
	public Map<String, String> getErrorFields() {
		// TODO Auto-generated method stub
		return null;
	}

	public static Author getByID(Integer key) {
		return ModelBase.getByID(Author.class, Integer.class, key);
	}

	public Integer getAuthorID() {
		return authorID;
	}

	public void setAuthorID(Integer authorID) {
		this.authorID = authorID;
	}

	public static List<Author> getAll() {
		return ModelBase.getAll(Author.class, Integer.class, "Author");
	}	
	
	public boolean equals(Object other) {
		if (other != null && other instanceof Author) {
			return this.authorID == ((Author)other).getAuthorID();
		}
		return super.equals(other);
	}

	public static List<Author> getByName(String name) {
		Criterion c = Restrictions.like("name", "%" + name + "%");
		List<Author> list = ModelBase.getByCriterion(Author.class, c);
		if (list == null) list = new ArrayList<Author>();
		return list;
	}
	
}
